#include "app_buzzer.h"

#define BUZZER_TOGGLE_COUNTS_MAX   (400)

volatile static app_buzzer_mgr_t buzzer_mgr = {0x00};

void app_buzzer_init(void)
{
    drv_buzzer_init();
    app_buzzer_start();
}


void TIM17_Init(void)
{
    // 1. 使能TIM17时钟
    LL_APB1_GRP2_EnableClock(LL_APB1_GRP2_PERIPH_TIM17);
    // 2. 配置TIM17为基本定时器
    LL_TIM_InitTypeDef TIM_InitStruct = {0};
    //TIM_InitStruct.Prescaler = 2 - 1;          // 2分频，4MHz计数频率(8MHz/2)
    TIM_InitStruct.Prescaler = 6 - 1;         
    TIM_InitStruct.CounterMode = LL_TIM_COUNTERMODE_UP;
    TIM_InitStruct.Autoreload = 1000 - 1;      // 1ms定时(1000个计数)   
    TIM_InitStruct.ClockDivision = LL_TIM_CLOCKDIVISION_DIV1;
    TIM_InitStruct.RepetitionCounter = 0;
    LL_TIM_Init(TIM17, &TIM_InitStruct);
    
    // 3. 配置更新中断
    LL_TIM_EnableIT_UPDATE(TIM17);
    NVIC_SetPriority(TIM17_IRQn, 0);
    NVIC_EnableIRQ(TIM17_IRQn);
    
    // 4. 启动定时器
    LL_TIM_EnableCounter(TIM17);
}

void TIM17_Stop(void)   //定时器停止
{
    // 1. 停止计数器
    LL_TIM_DisableCounter(TIM17);
    
    // 2. 禁用所有输出(如果用于PWM)
    LL_TIM_DisableAllOutputs(TIM17);
    
    // 3. 清除中断标志
    LL_TIM_ClearFlag_UPDATE(TIM17);
    
    // 注意: 保留中断使能状态以便重新启动
}

void app_buzzer_pwm_irq_handler(void)   //开蜂鸣器时中断翻转
{
    if(LL_TIM_IsActiveFlag_UPDATE(TIM17))
    {
        LL_TIM_ClearFlag_UPDATE(TIM17);
        drv_buzzer_toggle();
        buzzer_mgr.counts++;
        if (buzzer_mgr.counts >= BUZZER_TOGGLE_COUNTS_MAX)
        {
            app_buzzer_off();
        }
    }
}

void app_buzzer_start(void) //蜂鸣器开始响
{
	buzzer_mgr.counts = 0;
    buzzer_mgr.state  = APP_BUZZER_ON;
	TIM17_Init();
}

void app_buzzer_off(void)   //蜂鸣器不响
{
    drv_buzzer_set(DRV_BUZZER_OFF);
    buzzer_mgr.state     = APP_BUZZER_OFF;
    TIM17_Stop();
}

unsigned char app_get_buzzer_state(void)
{
    return buzzer_mgr.state;
}